import {
  AfterViewInit,
  ApplicationRef,
  Component,
  ElementRef,
  NgZone,
  ViewChild,
  inject,
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { CardComponent } from './cards/root-card.component';
import { fromEvent } from 'rxjs';
import { TriggerService } from './trigger.service';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, CardComponent],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements AfterViewInit {
  @ViewChild('tick') tickBtn!: ElementRef;
  @ViewChild('mutateInputInPlace') mutateInputBtn!: ElementRef;
  @ViewChild('newInputCopy') newInputBtn!: ElementRef;
  @ViewChild('triggerAsync') asyncBtn!: ElementRef;

  appRef = inject(ApplicationRef);
  ngZone = inject(NgZone);
  triggerService = inject(TriggerService);

  inputObj: { title: string } = { title: 'test' };

  ngAfterViewInit(): void {
    this.ngZone.runOutsideAngular(() => {
      fromEvent(this.tickBtn.nativeElement, 'click').subscribe(() => {
        this.appRef.tick();
      });
    });

    fromEvent(this.asyncBtn.nativeElement, 'click').subscribe(() => {
      this.triggerService.trigger();
    });

    fromEvent(this.mutateInputBtn.nativeElement, 'click').subscribe(() => {
      this.inputObj.title += '1';
    });

    fromEvent(this.newInputBtn.nativeElement, 'click').subscribe(() => {
      this.inputObj = { title: this.inputObj.title + '1' };
    });
  }
}
